package com.midongtech.cpd.utils;

import android.text.TextUtils;
import android.util.Base64;

import java.net.URLEncoder;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class CpdEncryptUtil {
    private static final String ENCRYPT_TYPE = "AES/ECB/PKCS5Padding";
    private static String ENCRYPT_KEY = "6666666666666666"; //此处为测试key，仅模拟测试用，需替换为幂动提供的真实key


    /**
     * 加密
     * @param plainText
     * @return
     */
    public static String encrypt(String plainText) {
        if (TextUtils.isEmpty(plainText)) {
            return "";
        }
        byte[] encrypt = null;
        try {
            Key key = generateKey(ENCRYPT_KEY);
            Cipher cipher = Cipher.getInstance(ENCRYPT_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            encrypt = cipher.doFinal(plainText.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64.encodeToString(encrypt, Base64.DEFAULT);
    }

    /**
     * 加密并编码
     * @param plainText
     * @return
     */
    public static String encryptAndEncode(String plainText) {
        if (TextUtils.isEmpty(plainText)) {
            return "";
        }
        byte[] encrypt = null;
        try {
            Key key = generateKey(ENCRYPT_KEY);
            Cipher cipher = Cipher.getInstance(ENCRYPT_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            encrypt = cipher.doFinal(plainText.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return URLEncoder.encode(Base64.encodeToString(encrypt, Base64.DEFAULT));
    }

    /**
     * 解密
     * @param keyStr
     * @param encryptData
     * @return
     */
    public static String decrypt(String keyStr, String encryptData) {
        byte[] decrypt = null;
        try {
            Key key = generateKey(keyStr);
            Cipher cipher = Cipher.getInstance(ENCRYPT_TYPE);
            cipher.init(Cipher.DECRYPT_MODE, key);
            decrypt = cipher.doFinal(Base64.decode(encryptData, Base64.DEFAULT));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decrypt != null ? new String(decrypt).trim() : "";
    }

    private static Key generateKey(String key) throws Exception {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            return keySpec;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

}
